package org.crag.cafca.gui.servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.crag.cafca.db.SqlConnector;

/**
 * Allows user to go into Cafca/* only if credentials are correct
 * @see web.xml
 *
 */
public class PrivateFilter implements Filter {
	
	/**
	 * Logger log4j. See log4j doc for more information.
	 */
	private static Logger log = Logger.getLogger(new Throwable().getStackTrace()[0].getClassName());

    public PrivateFilter() {}

	public void destroy() {}


	public void init(FilterConfig fConfig) throws ServletException 
	{

	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		/*Start the session*/
		HttpSession session = ((HttpServletRequest) request).getSession();
		
		/*If a session is already opened (useful for servlet access, so that there is no SQL request each time a servlet is called)*/
		if(session.getAttribute("username") != null)
		{
			log.info("Session is already open with username : "+session.getAttribute("username"));
			chain.doFilter(request, response);
		}
		
		/*Else, check if the user's credentials are correct*/
		else
		{
			/*Retrieve the data sent by login.js*/
			String username = ((HttpServletRequest) request).getParameter("username");
			String password = ((HttpServletRequest) request).getParameter("password"); 
			
			SqlConnector sqlConnector = new SqlConnector();		
			
			/*If the user is actually present in DB and its credentials are correct */
			if(sqlConnector.checkUsernameAndPassword(username, password))
			{
				sqlConnector.close(); 
				
				/*Set session's attribute, based on the username, because it's the only unique field*/			 
				session.setAttribute("username", username);	
				
				/*Load the timeline from db */
				SqlConnector connector=new SqlConnector();
				session.setAttribute("timeline", connector.loadTimeLine(username));
				connector.close();
				
				log.info("User "+session.getAttribute("username")+" is now connected. Timeline is loaded."); 
				chain.doFilter(request, response);
			}
						
			/*If there is no session, go to the login form*/
			else
			{
				sqlConnector.close();
				HttpServletResponse rep = (HttpServletResponse) response;
				rep.sendRedirect("/Cafca");			
			}
		}		
	}
}
